package com.sf.dlb.service;

import com.sf.dlb.bean.UserRquestBean;
import com.sf.dlb.config.Global;
import com.sf.dlb.constant.CacheConstant;
import com.sf.dlb.jpa.model.*;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.repository.*;
import com.sf.dlb.utils.*;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * Created by jing.tan on 2018/12/10.
 */
@Service
public class UserInfoService {
    private static Logger logger= LoggerFactory.getLogger(UserInfoService.class);

    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private SmsInfoService smsInfoService;
    @Autowired
    private NewRecodRepository newRecodRepository;
    @Resource
    private Global global;
    @Autowired
    private UserWalletRepository userWalletRepository;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private UserInvitationRepository userInvitationRepository;
    @Autowired
    private UserRealInfoRepository userRealInfoRepository;
    @Autowired
    private WalletEthAddressService walletEthAddressService;
    @Autowired
    private WalletEthAddressRepository walletEthAddressRepository;
    @Autowired
    private UserNewRepository userNewRepository;
    @Autowired
    private UserNewService userNewService;
    @Autowired
    public RedisUtil redisUtil;
    @Autowired
    private UserMessageService userMessageService;
    @Autowired
    private UserInvitationService userInvitationService;
    @Autowired
    private VideoRecordRepository videoRecordRepository;
    @Autowired
    private VisitorInfoService visitorInfoService;
    /**
     * token+校验
     *
     * @return
     */
    public ResultVO getTokenChekout(HttpServletRequest request) {
        logger.info("getTokenChekout start ");
        //判断token是否合法
        String token=request.getHeader(global.token_request_header_key);
        logger.info("getTokenChekout token === " + token);
        if(StringUtils.isEmpty(token)){
            return ResultVOUtil.error(ResponseConstant.ERROR_TOKEN_NULL, "token不能为空");
        }
        if(!token.startsWith(global.token_request_header_value_prefix)){
            return ResultVOUtil.error(ResponseConstant.ERROR_TOKEN_ILLEGAL, "token不合法");
        }
        if(token.length()<=global.token_request_header_value_prefix.length()+1){
            return ResultVOUtil.error(ResponseConstant.ERROR_TOKEN_ILLEGAL, "token不合法");
        }
        token=token.substring(global.token_request_header_value_prefix.length()+1);
        //Token认证
        ResultVO resultVO = checkoutToken(token);
        logger.info("getTokenChekout tokenEntity "+ GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }

    /**
     * 注册用户
     * @param userRquestBean
     * @return
     */
    @Transactional
    public ResultVO registerUser(UserRquestBean userRquestBean){
        logger.info("==registerUser start userRquestBean={}",GsonUtils.getInstance().toJson(userRquestBean));
        UserInfo userInfo;//注册完成，响应信息
        synchronized (userInfoRepository) {
            //手机号是否注册过
            userInfo = userInfoRepository.findByMobileAndDelFlag(userRquestBean.getMobile(), BaseEntity.DEL_FLAG);
            if (null != userInfo) {
                return ResultVOUtil.error(ResponseConstant.ERROR, "此用户已存在");
            } else {
                userInfo = new UserInfo();
            }
            //邀请码处理 1
            String inviteCode = userRquestBean.getInviteCode();
            //邀请码是否存在-没有邀请码不能注册
            UserInfo inviteCodeUserInfo = userInfoRepository.findByQrCodeAndDelFlag(inviteCode, "0");
            if (null == inviteCodeUserInfo) {
                return ResultVOUtil.error(ResponseConstant.ERROR, "此邀请码不存在");
            }
            //校验验证码
            ResultVO resultVO = smsInfoService.checkoutVerificationCode(userRquestBean.getMobile(), userRquestBean.getValidationCode());
            if (resultVO.getCode() != 200) {
                return resultVO;
            }
            //保存用户
            String qrCode=userInvitationService.generateInviteCode(); //生成邀请码
            Long userId = userInfoRepository.findByDelFlagCount();//生成用户ID
            userId = (userId != null) ? userId + 1 : 1;
            userInfo.setMobile(userRquestBean.getMobile());
            userInfo.setMobileMac(userRquestBean.getMac());
            userInfo.setUserId(userId.toString());
            userInfo.setName(ResponseConstant.user_default_nickname + "_" + qrCode);
            userInfo.setQrCode(qrCode);//二维码(邀请码)
            userInfo.setLoginFlag("0");
            userInfo.setUserGrade("0"); //等级默认为0
            userInfo.setDeviceNumber(userRquestBean.getDeviceNumber());
            userInfo.setCreateDate(new Date());
            userInfo.setUpdateDate(new Date());
            logger.info("registerUser save " + GsonUtils.getInstance().toJson(userInfo));
            userInfo = userInfoRepository.save(userInfo);
            // 更新用户钱包-注册奖励；只要用户注册，就会得到个dlb;
            userWalletService.updateUserWallet(userId + "", global.user_be_invitation_user_get_dlb, ResponseConstant.source_type_register, ResponseConstant.source_type_register_value);
            //更新邀请记录
            UserInvitationInfo userInvitationInfo = new UserInvitationInfo();
            userInvitationInfo.setUserId(inviteCodeUserInfo.getUserId());
            userInvitationInfo.setInvitationUserId(userInfo.getUserId());
            userInvitationInfo.setQrCode(inviteCode);
            userInvitationInfo.setState(ResponseConstant.user_invitation_registered);
            userInvitationInfo.setUserGetDlb(global.user_the_invitation_user_get_dlb);
            userInvitationInfo.setInvitationUserGetDlb(global.user_be_invitation_user_get_dlb);
            userInvitationInfo.setCreateDate(new Date());
            userInvitationInfo.setUpdateDate(new Date());
            userInvitationRepository.save(userInvitationInfo);
            logger.info("registerUser 邀请码处理 2 " + GsonUtils.getInstance().toJson(userInvitationInfo));
            //绑定一个eth钱包地址
            walletEthAddressService.banddingUserAndAddress(userInfo.getUserId());
            //初始化用户新闻阅读
            userNewService.initUserNewInfo(userId.toString());
        }
        TokenEntity tokenEntity=generaAndSaveToken(userInfo.getUserId(),DateUtils.formatDate(new Date()));
        UserVO userVO=userBeanToVo(userInfo,tokenEntity);
        return ResultVOUtil.success(userVO);
    }
    /**
     * 验证码登录
     * @param userRquestBean
     * @return
     */
    public ResultVO loginVerificationCode(UserRquestBean userRquestBean){
        logger.info("==loginVerificationCode start userRquestBean={}",GsonUtils.getInstance().toJson(userRquestBean));
        //手机号是否存在
        UserInfo userInfo=userInfoRepository.findByMobileAndDelFlag(userRquestBean.getMobile(), BaseEntity.DEL_FLAG);
        if(null==userInfo){
            return ResultVOUtil.error(ResponseConstant.ERROR,"用户不存在，请下载使用最新版本！");
        }
        //校验验证码
        ResultVO resultVO=smsInfoService.checkoutVerificationCode(userRquestBean.getMobile(),userRquestBean.getValidationCode());
        if(resultVO.getCode()!=200){
            //登录错误次数记录
            handlerLoginErrorNumber(userRquestBean.getMobile());
            return resultVO;
        }
        //如果传了设备号-绑定设备号，更新游客信息
        userInfo.setDeviceNumber(userRquestBean.getDeviceNumber());
        userInfo.setUpdateDate(new Date());
        userInfoRepository.save(userInfo);
        visitorInfoService.updateRegistFlag(userRquestBean.getDeviceNumber());
        //生成token
        TokenEntity tokenEntity=generaAndSaveToken(userInfo.getUserId(),DateUtils.formatDate(new Date()));
        logger.info("loginVerificationCode token == "+GsonUtils.getInstance().toJson(tokenEntity));
        UserVO userVO=userBeanToVo(userInfo,tokenEntity);
        return ResultVOUtil.success(userVO);
    }
    /**
     * 密码登录
     * @param userRquestBean
     * @return
     */
    public ResultVO loginPasswrod(UserRquestBean userRquestBean){
        logger.info("==loginPasswrod start userRquestBean={}",GsonUtils.getInstance().toJson(userRquestBean));
        //手机号是否存在
        UserInfo userInfo=userInfoRepository.findByMobileAndDelFlag(userRquestBean.getMobile(), BaseEntity.DEL_FLAG);
        if(null==userInfo){
            return ResultVOUtil.error(ResponseConstant.ERROR,"此用户不存在，请下载使用最新版本！");
        }
        //校验密码
        if(StringUtils.isBlank(userInfo.getLoginPassword())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"未设置登入密码，请前往\"我的-设置\"进行设置");
        }
        boolean validatePassword=SecurityUtils.validatePassword(userRquestBean.getLoginPassword(),userInfo.getLoginPassword());
        if(validatePassword){
            //如果传了设备号-绑定设备号，更新游客信息
            userInfo.setDeviceNumber(userRquestBean.getDeviceNumber());
            userInfo.setUpdateDate(new Date());
            userInfoRepository.save(userInfo);
            visitorInfoService.updateRegistFlag(userRquestBean.getDeviceNumber());
            //生成token
            TokenEntity tokenEntity=generaAndSaveToken(userInfo.getUserId(),DateUtils.formatDate(new Date()));
            logger.info("loginPasswrod token == "+GsonUtils.getInstance().toJson(tokenEntity));
            UserVO userVO=userBeanToVo(userInfo,tokenEntity);
            return ResultVOUtil.success(userVO);
        }else{
            handlerLoginErrorNumber(userRquestBean.getMobile());
            return ResultVOUtil.error(ResponseConstant.ERROR,"密码错误");
        }
    }
    /**
     * 生成toekn
     *
     * @param userId
     * @param createDate
     * @return
     */
    public TokenEntity generaToken(String userId,String createDate,String uuid){
        TokenEntity tokenEntity=new TokenEntity();
        String token=MD5Util.MD5(userId+createDate+uuid);
        Date tokenCreateDate=new Date();
        tokenEntity.setToken(token);
        tokenEntity.setCreateDate(tokenCreateDate);
        tokenEntity.setExpiresIn(Long.valueOf(global.token_valid_time));
        tokenEntity.setUserId(userId);
        return tokenEntity;
    }
    /**
     * 生成并保存token
     *
     * @param userId
     * @param createDate
     * @return
     */
    public TokenEntity generaAndSaveToken(String userId,String createDate){
        String uuid=UUID.randomUUID().toString().replace("-","");
        TokenEntity tokenEntity=generaToken(userId,createDate,uuid);
        UserInfo userInfo = userInfoRepository.findByUserIdAndDelFlag(tokenEntity.getUserId(),"0");
        userInfo.setToken(tokenEntity.getToken());
        userInfo.setTokenTime(tokenEntity.getCreateDate());
        userInfo.setUpdateDate(new Date());
        userInfoRepository.save(userInfo);
        return tokenEntity;
    }
    /**
     * 生成并保存token
     *
     * @param token
     * @return
     */
    public TokenEntity generaAndSaveToken(String token){
        String uuid=UUID.randomUUID().toString().replace("-","");
        String currentStr=DateUtils.formatDate(new Date());
        UserInfo userInfo = userInfoRepository.findByTokenAndDelFlag(token,"0");
        TokenEntity tokenEntity=generaToken(userInfo.getUserId(),currentStr,uuid);
        userInfo.setToken(tokenEntity.getToken());
        userInfo.setTokenTime(tokenEntity.getCreateDate());
        userInfo.setUpdateDate(new Date());
        userInfoRepository.save(userInfo);
        return tokenEntity;
    }
    /**
     * 登录错误次数+1
     * @param mobile
     */
    public void handlerLoginErrorNumber(String mobile){
        logger.info("handlerLoginErrorNumber start mobile={}",mobile);
        String key= CacheConstant.USER_CACHE+CacheConstant.USER_LOGIN_ERROR_NUMBER+mobile;
        boolean existFlag=redisUtil.hasKey(key);//判断key是否存在
        if(existFlag){
            redisUtil.incr(key,1);
        }else{
            long seconds=DateUtils.currentDistance24Long()/1000;//毫秒转成秒
            redisUtil.set(key,1,seconds);
        }
    }
    /**
     * 判断是否登录错误次数>5
     * @param mobile
     * @return false=否 true=是
     */
    public boolean isLoginErrorNumber(String mobile){
        logger.info("isLoginErrorNumber start mobile={}",mobile);
        String key=CacheConstant.USER_CACHE+CacheConstant.USER_LOGIN_ERROR_NUMBER+mobile;
        boolean existFlag=redisUtil.hasKey(key);//判断key是否存在
        if(existFlag){
            Integer errorCount=(Integer)redisUtil.get(key);
            if(errorCount>global.user_login_error_number){
                return true;
            }
        }
        return false;
    }
    /**
     * 判断是否被预警-禁止3天
     * @param mobile
     * @return false=否 true=是
     */
    public boolean isWarningForBid(String mobile){
        logger.info("isWarningForBid start mobile={}",mobile);
        UserInfo userInfo=userInfoRepository.findByMobileAndDelFlag(mobile,"0");
        if(null==userInfo){
            return false;
        }
        String userId=userInfo.getUserId();
        String key=CacheConstant.USER_CACHE+CacheConstant.BAN_USER_3DAY_LOGIN+userId;
        boolean existFlag= redisUtil.hasKey(key);
        if(existFlag){
            return true;
        }
        return false;
    }
    /**
     * 判断是否被预警-冻结
     * @param mobile
     * @return false=否 true=是
     */
    public boolean isFreezeLogin(String mobile){
        logger.info("isFreezeLogin start mobile={}",mobile);
        UserInfo userInfo=userInfoRepository.findByMobileAndDelFlag(mobile,"0");
        if(null==userInfo){
            return false;
        }
        String loginFlag=userInfo.getLoginFlag();
        if(StringUtils.equals(loginFlag,"0")){
            return false;
        }
        return true;
    }
    /**
     * 根据Token查找用户
     *
     * @param tokenEntity
     * @return
     */
    public ResultVO findByUserAndToken(TokenEntity tokenEntity){
        logger.info("findByUserAndToken tokenEntity "+GsonUtils.getInstance().toJson(tokenEntity));
        String userId=tokenEntity.getUserId();
        UserInfo userInfo=userInfoRepository.findByUserIdAndDelFlag(userId,"0");
        UserVO userVO=userBeanToVo(userInfo,tokenEntity);
        logger.info("findByUserAndToken end "+GsonUtils.getInstance().toJson(userVO));
        return ResultVOUtil.success(userVO);

    }
    /**
     * 检验token
     * @param token
     * @return
     */
    public ResultVO checkoutToken(String token){
        //token是否存在
        UserInfo userInfo = userInfoRepository.findByTokenAndDelFlag(token,"0");
        if(null==userInfo){
            return ResultVOUtil.error(ResponseConstant.ERROR_TOKEN_THERE_NO, "token不存在");
        }
        //用户是否被禁止
        boolean forBidFlag=isWarningForBid(userInfo.getMobile());
        if(forBidFlag){
            return ResultVOUtil.error(ResponseConstant.ERROR_TOKEN_FORBID_3DAY_LOGIN, "token被禁止");
        }
        //用户是否被冻结
        boolean freezeLogin=isFreezeLogin(userInfo.getMobile());
        if(freezeLogin){
            return ResultVOUtil.error(ResponseConstant.ERROR_TOKEN_FREEZE, "token被冻结");
        }
        TokenEntity tokenEntity=new TokenEntity();
        tokenEntity.setUserId(userInfo.getUserId());
        tokenEntity.setToken(userInfo.getToken());
        tokenEntity.setCreateDate(userInfo.getTokenTime());
        tokenEntity.setExpiresIn(Long.valueOf(global.token_valid_time));
        //toKen是否过期
        Date createDate=userInfo.getTokenTime();
        Date currntDate=new Date();
        Long expiresIn=Long.valueOf(global.token_valid_time);
        long timeDifference=(currntDate.getTime()-createDate.getTime())/1000;
        if(timeDifference>expiresIn) {
            logger.info("token已过期");
            return ResultVOUtil.error(ResponseConstant.ERROR_TOKEN_OVERDUE, "token已过期");
        }
        return ResultVOUtil.success(tokenEntity);
    }
    /**
     * 修改用户
     * @param userRquestBean
     * @return
     */
    public ResultVO updateUser(UserRquestBean userRquestBean,TokenEntity tokenEntity) {
        logger.info("==updateUser start userRquestBean={}",GsonUtils.getInstance().toJson(userRquestBean));
        String userId = tokenEntity.getUserId();
        UserInfo userInfo = userInfoRepository.findByUserIdAndDelFlag(userId, "0");
        if (null == userInfo) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "用户不存在");
        }
        if (StringUtils.isNotBlank(userRquestBean.getName())) {
            //修改昵称
            userInfo.setName(userRquestBean.getName());
        }else if (StringUtils.isNotBlank(userRquestBean.getUserProfiles())) {
            //修改个人简介
            userInfo.setUserProfiles(userRquestBean.getUserProfiles());
        } else if (StringUtils.isNotBlank(userRquestBean.getMobile())) {
            //修改手机
            //校验新手机和验证码是否正确；
            ResultVO resultVO = smsInfoService.checkoutVerificationCode(userRquestBean.getMobile(), userRquestBean.getValidationCode());
            if (resultVO.getCode()!=200) {
                return resultVO;
            }
            //新的手机已经被注册了
            UserInfo userInfo1 = userInfoRepository.findByMobileAndDelFlag(userRquestBean.getMobile(), "0");
            if (null != userInfo1) {
                return ResultVOUtil.error(ResponseConstant.ERROR, "此手机号已存在");
            }
            userInfo.setMobile(userRquestBean.getMobile());
        } else if (StringUtils.isNotBlank(userRquestBean.getLoginPassword())) {
            //登录密码
            //之前是否设置过密码
            String loginPassword = userInfo.getLoginPassword();
            if (StringUtils.isNotBlank(loginPassword)) {
                String loginPasswrodOld = userRquestBean.getLoginPasswordOld();
                boolean validatePwdFlag = SecurityUtils.validatePassword(loginPasswrodOld, loginPassword);
                if (!validatePwdFlag) {
                    return ResultVOUtil.error(ResponseConstant.ERROR, "旧密码输错误");
                }
            }
            userInfo.setLoginPassword(SecurityUtils.entryptPassword(userRquestBean.getLoginPassword()));
        } else if (StringUtils.isNotBlank(userRquestBean.getPayPassword())) {
            //支付密码
            String payPassword = userInfo.getPayPassword();
            if (StringUtils.isNotBlank(payPassword)) {
                String payPasswrodOld = userRquestBean.getPayPasswordOld();
                boolean validatePwdFlag = SecurityUtils.validatePassword(payPasswrodOld, payPassword);
                if (!validatePwdFlag) {
                    return ResultVOUtil.error(ResponseConstant.ERROR, "旧密码输入错误");
                }
            }
            userInfo.setPayPassword(SecurityUtils.entryptPassword(userRquestBean.getPayPassword()));
        }else{
            return ResultVOUtil.error(ResponseConstant.ERROR, "没有修改信息");
        }
        logger.info("updateUser userInfo "+GsonUtils.getInstance().toJson(userInfo));
        userInfo.setUpdateDate(new Date());
        userInfo = userInfoRepository.save(userInfo);
        UserVO userVO=userBeanToVo(userInfo,tokenEntity);
        return ResultVOUtil.success(userVO);
    }
    /**
     * 上传头像
     * @param multipartHttpServletRequest
     * @return
     */
    public ResultVO uploadUserPhoto(MultipartHttpServletRequest multipartHttpServletRequest,TokenEntity tokenEntity) {
        String userId=tokenEntity.getUserId();
        UserInfo userInfo = userInfoRepository.findByUserIdAndDelFlag(userId,"0");

        String absolutePath=global.getUser_image_absolute_path(userId);
        FileUtils.createDirectory(absolutePath.toString());
        Iterator<String> iter=multipartHttpServletRequest.getFileNames();
        while (iter.hasNext()){
            MultipartFile multipartFile=multipartHttpServletRequest.getFile(iter.next().toString());
            logger.info("uploadUserPhoto multipartFile.getName()={}",multipartFile.getName());
            if(null!=multipartFile && !multipartFile.isEmpty()){
                String multipartFileName=UUID.randomUUID().toString()+".png";//multipartFile.getOriginalFilename();
                String localFileName=absolutePath+"/"+multipartFileName;
                String relativeFileName=new StringBuffer().append(global.getUser_image_relative_path(userId)).append("/").append(multipartFileName).toString();
                File localFile=new File(localFileName);
                try {
                    logger.info("multipartFile multipartFile.getBytes().length={}",multipartFile.getBytes().length);
                    multipartFile.transferTo(localFile);
                    userInfo.setPhoto(relativeFileName);
                    userInfo.setUpdateDate(new Date());
                    userInfo=userInfoRepository.save(userInfo);
                    logger.info("uploadUserPhoto userInfo "+GsonUtils.getInstance().toJson(userInfo));
                    UserVO userVO=userBeanToVo(userInfo,tokenEntity);
                    return ResultVOUtil.success(userVO);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info("上传图片失败");
                }
            }
        }
        return ResultVOUtil.error(ResponseConstant.ERROR,"上传图片失败");
    }
    /**
     * 检验支付密码
     * @return
     */
    public ResultVO checkoutPayPassword(String oldPayPassword,String newPayPassword){
        logger.info("checkoutPayPassword  oldPayPassword = "+oldPayPassword+" & newPayPassword = "+newPayPassword);
        if(StringUtils.isBlank(oldPayPassword)||StringUtils.isBlank(newPayPassword)){
            return ResultVOUtil.error(ResponseConstant.ERROR,"支付密码为空");
        }
        boolean payPasswordFlag=SecurityUtils.validatePassword(newPayPassword,oldPayPassword);
        if(!payPasswordFlag){
            return ResultVOUtil.error(ResponseConstant.ERROR,"支付密码错误");
        }
        return ResultVOUtil.success();
    }
    /**
     * 修改登录密码
     * @return
     */
    public ResultVO updateLoginPassword(UserRquestBean userRquestBean){
        logger.info("==updateLoginPassword start userRquestBean={}",GsonUtils.getInstance().toJson(userRquestBean));
        //校验手机号，验证码
        String mobile=userRquestBean.getMobile();
        String validationCode=userRquestBean.getValidationCode();
        String loginPassword=userRquestBean.getLoginPassword();
        UserInfo userInfo=userInfoRepository.findByMobileAndDelFlag(mobile,"0");
        if(null==userInfo){
            logger.info("updatePassword userInfo is null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"用户不存在");
        }
        ResultVO smsResultVO=smsInfoService.checkoutVerificationCode(mobile,validationCode);
        if(smsResultVO.getCode()!=200){
            handlerLoginErrorNumber(mobile);//防止暴力重置密码
            logger.info("updatePassword smsResultVO.getCode()!=200");
            return smsResultVO;
        }
        //修改支付密码
        userInfo.setLoginPassword(SecurityUtils.entryptPassword(loginPassword));
        userInfo.setUpdateDate(new Date());
        userInfoRepository.save(userInfo);
        return ResultVOUtil.success();
    }
    /**
     * 修改支付密码
     * @return
     */
    public ResultVO updatePayPassword(UserRquestBean userRquestBean,TokenEntity tokenEntity){
        logger.info("==updatePayPassword start userRquestBean={}",GsonUtils.getInstance().toJson(userRquestBean));
        //校验手机号，验证码
        String validationCode=userRquestBean.getValidationCode();
        String loginPassword=userRquestBean.getLoginPassword();
        String payPassword=userRquestBean.getPayPassword();
        String userId=tokenEntity.getUserId();
        UserInfo userInfo=userInfoRepository.findByUserIdAndDelFlag(userId,"0");
        if(null==userInfo){
            logger.info("updatePassword userInfo is null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"用户不存在");
        }
        //验证登录密码
        String securityLoginPassword=userInfo.getLoginPassword();
        if(StringUtils.isBlank(securityLoginPassword)){
            logger.info("updatePassword securityLoginPassword 用户未设置登录密码");
            return ResultVOUtil.error(ResponseConstant.ERROR,"用户未设置登录密码");
        }
        if(!SecurityUtils.validatePassword(loginPassword,securityLoginPassword)){
            logger.info("updatePassword validatePassword 登录密码错误");
            return ResultVOUtil.error(ResponseConstant.ERROR,"登录密码错误");
        }
        //验证，验证码
        String mobile=userInfo.getMobile();
        ResultVO smsResultVO=smsInfoService.checkoutVerificationCode(mobile,validationCode);
        if(smsResultVO.getCode()!=200){
            logger.info("updatePassword smsResultVO.getCode()!=200");
            return smsResultVO;
        }
        //修改支付密码
        userInfo.setPayPassword(SecurityUtils.entryptPassword(payPassword));
        userInfo.setUpdateDate(new Date());
        userInfoRepository.save(userInfo);
        return ResultVOUtil.success();
    }
    /**
     * 用户实名认证
     * @return
     */
    public ResultVO updateUserRealInfo(UserRquestBean userRquestBean,TokenEntity tokenEntity){
        logger.info("==updatePayPassword start userRquestBean={}",GsonUtils.getInstance().toJson(userRquestBean));
        String userId=tokenEntity.getUserId();
        //查询用户是否已经实名了；已经实名了，不可以继续修改；驳回的状态，可以修改；
        UserRealInfo userRealInfo=userRealInfoRepository.findByUserIdAndDelFlag(userId,"0");
        if(userRealInfo!=null){
            if(!userRealInfo.getState().equals("4")){
                logger.info("updatePayPassword 用户已经实名认证了");
                return ResultVOUtil.error(ResponseConstant.ERROR,"用户已经实名认证了");
            }
        }
        //获取图片
        String name=userRquestBean.getName();
        String idNumber=userRquestBean.getIdNumber();
        StringBuffer idNumberImages=new StringBuffer();
        String absolutePath=global.getUser_image_absolute_path(userId);
        FileUtils.createDirectory(absolutePath.toString());
        MultipartFile[] multipartFiles=userRquestBean.getFile();
        for(MultipartFile multipartFile:multipartFiles){
            if(null!=multipartFile&&!multipartFile.isEmpty()){
                String multipartFileNameStr=UUID.randomUUID().toString()+".png";
                String localFileNameStr=absolutePath+"/"+multipartFileNameStr;
                String relativeFileName=new StringBuffer().append(global.getUser_image_relative_path(userId)).append("/").append(multipartFileNameStr).toString();
                File file=new File(localFileNameStr);
                try {
                    multipartFile.transferTo(file);
                    idNumberImages.append(relativeFileName).append(",");
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info("上传图片失败");
                }
            }else{
                logger.info("updatePayPassword multipartFile is null");
            }
        }
        //是否上传了图片
        if(idNumberImages.toString().length()<=0){
            logger.info("updatePayPassword 未上传图片 ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"未上传图片");
        }
        //去掉最后的逗号；
        String idNumberImage=idNumberImages.toString();
        idNumberImage=idNumberImage.substring(0,idNumberImage.length()-1);
        //保存用户实名信息
        UserRealInfo tempUserRealInfo=(userRealInfo==null?new UserRealInfo():userRealInfo);
        tempUserRealInfo.setUserId(userId);
        tempUserRealInfo.setName(name);
        tempUserRealInfo.setIdNumberType("1");//默认证件=身份证
        tempUserRealInfo.setIdNumber(idNumber);
        tempUserRealInfo.setIdNumberImage(idNumberImage);
        tempUserRealInfo.setState("2");//默认审核中
        tempUserRealInfo.setCreateDate((userRealInfo==null?new Date():userRealInfo.getCreateDate()));
        tempUserRealInfo.setUpdateDate(new Date());
        userRealInfoRepository.save(tempUserRealInfo);
        return ResultVOUtil.success();
    }
    /**
     * 用户登出
     * @return
     */
    public ResultVO logout(String userId){
        logger.info("==logout start userId={}",userId);
        UserInfo userInfo=userInfoRepository.findByUserIdAndDelFlag(userId,"0");
        userInfo.setToken(null);
        userInfo.setUpdateDate(new Date());
        userInfoRepository.save(userInfo);
        return ResultVOUtil.success();
    }
    /**
     * VO转换
     * @return
     */
    public UserVO userBeanToVo(UserInfo userInfo,TokenEntity tokenEntity){
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(userInfo,userVO);
        userVO.setPhoto(StringUtils.isNotBlank(userVO.getPhoto())?global.file_public_ip +userVO.getPhoto():userVO.getPhoto());
        userVO.setToken(tokenEntity.getToken());
        userVO.setLoginPassword(StringUtils.isNotBlank(userInfo.getLoginPassword())?"0":"1");
        userVO.setPayPassword(StringUtils.isNotBlank(userInfo.getPayPassword())?"0":"1");
        userVO.setQrCodePath(global.user_share_url+userInfo.getQrCode());
        //实名状态
        UserRealInfo userRealInfo=userRealInfoRepository.findByUserIdAndDelFlag(userInfo.getUserId(),"0");
        String realState="1";
        String rejectDesc="";
        if(null!=userRealInfo){
            realState=userRealInfo.getState();
            rejectDesc=userRealInfo.getRejectDesc();
        }
        userVO.setRealState(realState);
        userVO.setRealStateValue(StateToValueUtils.switchRealStateValue(userVO.getRealState()));
        userVO.setRejectDesc(rejectDesc);
        //用户等级过期时间
        Long gradeValidityTime=(null==userInfo.getGradeValidityTime()?0L:userInfo.getGradeValidityTime().getTime());
        userVO.setGradeValidityTime(gradeValidityTime);
        //VO封装：计算每日数量，时间，累计时间，dlb，历史数量;
        countEveryData(userVO);
        return userVO;
    }
    /**
     * 计算我的-每日数据
     */
    private void countEveryData(UserVO userVO) {
        logger.info("countEveryData userVO={}",GsonUtils.getInstance().toJson(userVO));
        String userId=userVO.getUserId();
        //统计总数
        UserNewInfo userNewInfo= userNewRepository.findByUserIdAndDelFlag(userId,"0");
        Double historyDlbCount=null;
        Integer ReadTimeCount=null;
        if(null!=userNewInfo){
            historyDlbCount=userNewInfo.getHistoryGetdlbCount();
            ReadTimeCount=userNewInfo.getReadTimeLong();
        }
        //统计每日
        String currentTime=DateUtils.getDate();
        Double everyDayDlbNews=newRecodRepository.getEveryDayReadGetdlb(userId,currentTime, "1","0");
        Double everyDayDlbVideo=videoRecordRepository.getEveryDayVideoGetdlb(userId,currentTime, "1","0");
        everyDayDlbNews=(everyDayDlbNews==null?0.0:everyDayDlbNews);
        everyDayDlbVideo=(everyDayDlbVideo==null?0.0:everyDayDlbVideo);
        Double everyDayDlb=Arith.add(everyDayDlbNews,everyDayDlbVideo);
        Integer everyDayReadNumer= newRecodRepository.findByEveryDayReadNumber(userId,currentTime,"0","1");
        Integer everyDayVideoNumber=videoRecordRepository.findByEveryDayVideoNumber(userId,currentTime,"0","1");
        userVO.setHistoryDlbCount(StringFormatUtils.kill3Decimals(historyDlbCount));
        userVO.setEveryDayDlb(StringFormatUtils.kill3Decimals(everyDayDlb));
        userVO.setEveryDayReadNumer((null==everyDayReadNumer?0:everyDayReadNumer)+"篇");
        userVO.setEveryDayVideoNumber(everyDayVideoNumber+"条");
        userVO.setReadTimeCount(DateUtils.timeFormatHourAndMin(ReadTimeCount));
        //用户的eth地址
        WalletEthAddressInfo walletEthAddressInfo=walletEthAddressRepository.findByUserIdAndDelFlag(userId,"0");
        if(null==walletEthAddressInfo){
            logger.info("countEveryData walletEthAddressInfo is null user={}",userId);
        }else {
            userVO.setEthAddress(walletEthAddressInfo.getAddress());
        }
        //用户是否有最新消息
        userVO.setUserMessage(userMessageService.isLatestMessage(userId)?"1":"0");
    }
}
